import React, { Component } from 'react'
import {
  StyleSheet,
  View,
  Text,
  Image,
  SectionList,
  TouchableOpacity
} from 'react-native'
import Toast from 'react-native-simple-toast'
import { connect } from 'react-redux'
import HeaderDefault from '../../components/header/HeaderDefault'
import { theme_app, theme_text } from '../../utils/appTheme'

import { getLineAdvTask, submitLineAdvTask } from '../../netServer/arrangeDrug'
import { birthdayToAges } from '../../utils/utils_date'

class ArrangeDrug extends Component {
  constructor(props) {
    super(props)
    this.state = {
      advList: [],
      adv_pending: [],
      adv_Processed: [],
      updateSeletedStatus: 1,
      isSeletedAll: false
    }
  }
  static navigationOptions = ({ navigation }) => ({
    header: <HeaderDefault backBtnOnPress={navigation.goBack} title="排药" />
  })

  componentDidMount() {
    this._loadDataAdvTask()
  }

  _loadDataAdvTask = () => {
    this.setState({
      advList: [],
      adv_pending: [],
      adv_Processed: []
    })

    let params = new FormData()
    params.append(
      'mainTaskId',
      this.props.navigation.state.params.taskMain.mainTaskId
    )

    getLineAdvTask(params, resp => {
      let { code, data = [], msg } = resp

      if (code == 0) {
        this._handeleNetData(data)
      } else {
        Toast.showWithGravity(msg, 0.3, Toast.CENTER)
      }
    })
  }

  _handeleNetData = data => {
    let temArr1 = []
    let temArr2 = []

    data.forEach(element => {
      if (element.status === '待执行') {
        temArr1.push(element)
      } else {
        temArr2.push(element)
      }
    })

    this.setState({
      advList: data,
      adv_pending: temArr1,
      adv_Processed: temArr2
    })
  }
  _renderItem = item => {
    return (
      <View
        style={{
          width: screenWidth,
          height: 80,
          flexDirection: 'row',
          borderBottomColor: '#efefef',
          borderBottomWidth: 1,
          backgroundColor: 'white',
          paddingLeft: 10,
          paddingRight: 10
        }}
      >
        <View style={{ width: screenWidth - 120, height: 80 }}>
          <View style={styles.lineStyle}>
            <Text style={{ fontSize: 16 }}>{item.name}</Text>

            <Text style={{ marginLeft: 25 }}>
              {item.sex == 1 ? '男' : '女'}/{birthdayToAges(item.birthday)}
            </Text>

            <Text style={{ marginLeft: 25 }}>{item.bed_no}</Text>
          </View>

          <View style={styles.lineStyle}>
            <Text style={{ width: 150 }}>诊断：{item.diagnose}</Text>

            <Text style={{ marginLeft: 25, color: 'red' }}>{item.allergy}</Text>
          </View>
        </View>

        <View style={{ width: 100, height: 80, flexDirection: 'row' }}>
          <View
            style={{
              width: 40,
              height: 80,
              justifyContent: 'center',
              alignItems: 'center'
            }}
          >
            {item.name === '王小翠' ? (
              <Image
                source={require('./src/shenhe.png')}
                style={{ width: 40, height: 40 }}
              />
            ) : null}
          </View>
          <View
            style={{
              width: 60,
              height: 80,
              justifyContent: 'center',
              alignItems: 'center'
            }}
          >
            <Text style={{ fontSize: 20 }}>
              {/* {item.hasAdvNum}/{item.totalAdvNum} */}
            </Text>
          </View>
        </View>
      </View>
    )
  }

  _renderFlistItem = ({ item, index, section }) => {
    let seletIcon = item.isSeleted
      ? require('./src/xuanze1.png')
      : require('./src/xuanze.png')
    let userName = ''
    let freqCode = ''

    return (
      <View
        style={{
          width: screenWidth,
          borderBottomColor: '#efefef',
          borderBottomWidth: 1,
          backgroundColor: 'white',
          flexDirection: 'row'
        }}
      >
        <View
          style={{
            paddingLeft: 10,
            paddingRight: 10,
            width: 0.6 * screenWidth,
            flexDirection: 'row',
            alignItems: 'center'
          }}
        >
          {item.status === '待执行' ? (
            <TouchableOpacity
              style={{
                width: 40,
                height: 40,
                justifyContent: 'center',
                alignItems: 'center'
              }}
              onPress={() => {
                item.isSeleted = !item.isSeleted
                this._freshSeletedStatus()
              }}
            >
              <Image style={{ width: 30, height: 30 }} source={seletIcon} />
            </TouchableOpacity>
          ) : null}

          <View style={{ flex: 1 }}>
            {item.adviseList.map((value, index) => {
              userName = value.usageName
              freqCode = value.freqCode

              let status_name = value.status_name

              return (
                <View
                  style={{
                    borderBottomColor: '#f1f1f1',
                    borderBottomWidth: 1,
                    paddingLeft: 10
                  }}
                  key={index}
                >
                  <Text style={{ paddingBottom: 5, paddingTop: 5 }}>
                    {value.medName}&nbsp;&nbsp;&nbsp;&nbsp;
                    <Text style={{ color: 'red' }}>
                      {status_name === '进行中' ? '' : status_name}
                    </Text>
                  </Text>
                  <Text style={{ paddingBottom: 5, paddingTop: 5 }}>
                    {value.standard}/{value.use_unit} &nbsp;&nbsp;&nbsp;&nbsp;
                    {value.measure}
                  </Text>
                </View>
              )
            })}
          </View>
        </View>
        <View
          style={{
            flex: 1,

            flexDirection: 'row',
            alignItems: 'center'
          }}
        >
          <Text>{userName}</Text>

          <Text>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{freqCode}
          </Text>
        </View>
      </View>
    )
  }

  _freshSeletedStatus = () => {
    let marr = this.state.updateSeletedStatus + 1
    let isAllSelet = true

    this.state.adv_pending.forEach(element => {
      if (!element.isSeleted) {
        isAllSelet = false
      }
    })

    this.setState({
      updateSeletedStatus: marr,
      isSeletedAll: isAllSelet
    })
  }

  _controlSeletedStatu = () => {
    this.state.adv_pending.forEach(element => {
      element.isSeleted = !this.state.isSeletedAll
    })

    this._freshSeletedStatus()
  }
  // paramss.append('data[' + index + '][name]', element.name)
  _commitAdv = () => {
    // mainid
    let params = new FormData()
    params.append(
      'mainTaskId',
      this.props.navigation.state.params.taskMain.mainTaskId
    )

    // userid
    let { user_id } = this.props.user_info
    params.append('userId', user_id)

    // taskid
    let tempASrr = []
    let markIndex = 0
    let isBreackStr = null

    for (let index = 0; index < this.state.adv_pending.length; index++) {
      const element = this.state.adv_pending[index]
      if (element.isSeleted) {
        // asd
        element.adviseList.forEach(elements => {
          if (elements.status_name !== '进行中') {
            isBreackStr = elements.status_name
          }
        })

        tempASrr.push(element.task_id)

        params.append('taskIds[' + markIndex + ']', element.task_id)
        markIndex++
      }
    }

    if (isBreackStr) {
      let art = `医嘱${isBreackStr}`
      Toast.showWithGravity(art, 0.3, Toast.CENTER)

      return
    }

    if (tempASrr.length > 0) {
      submitLineAdvTask(params, resp => {
        let { code, msg } = resp

        if (code == '0') {
          Toast.showWithGravity('数据提交成功', 0.3, Toast.CENTER)
          this.props.navigation.state.params.callBack()
          this._loadDataAdvTask()
        } else {
          Toast.showWithGravity(msg, 0.3, Toast.CENTER)
        }
      })
    } else {
      Toast.showWithGravity('请选择你要提交的排药任务', 0.3, Toast.CENTER)
      return
    }
  }

  _keyExtractor = (item, index) => item.task_id + 'task'

  _separator = () => {
    return <View style={{ height: 1, backgroundColor: '#efefef' }} />
  }

  render() {
    let seletIcon = this.state.isSeletedAll
      ? require('./src/xuanze1.png')
      : require('./src/xuanze.png')
    return (
      <View style={styles.container}>
        {this._renderItem(this.props.navigation.state.params.taskMain)}

        <SectionList
          style={{ flex: 1 }}
          renderItem={this._renderFlistItem}
          renderSectionHeader={({ section: { title } }) => (
            <View
              style={{
                width: screenWidth,
                height: 50,
                backgroundColor: 'white',
                borderBottomWidth: 1,
                borderBottomColor: '#efefef',
                paddingLeft: 10,
                paddingRight: 10,
                flexDirection: 'row',
                justifyContent: 'space-between',
                alignItems: 'center'
              }}
            >
              <Text style={{ fontWeight: 'bold' }}>{title}</Text>
              <Image
                style={{ width: 25, height: 25 }}
                source={require('./src/jiantou.png')}
              />
            </View>
          )}
          sections={[
            { title: '未排', data: this.state.adv_pending },
            { title: '已排', data: this.state.adv_Processed }
          ]}
          extraData={this.state.updateSeletedStatus}
          keyExtractor={(item, index) => item + index}
        />

        <View
          style={{
            width: screenWidth,
            height: 45,
            borderTopColor: '#9b9b9b',
            borderTopWidth: 1,
            flexDirection: 'row'
          }}
        >
          <TouchableOpacity
            onPress={this._controlSeletedStatu}
            style={{
              width: 60,
              height: 45,
              borderRightColor: '#9b9b9b',
              borderRightWidth: 1,
              justifyContent: 'center',
              alignItems: 'center'
            }}
          >
            <Image style={{ width: 30, height: 30 }} source={seletIcon} />
          </TouchableOpacity>
          <TouchableOpacity
            onPress={this._commitAdv}
            style={{
              width: screenWidth - 60,
              height: 45,
              justifyContent: 'center',
              alignItems: 'center'
            }}
          >
            <Text style={{ fontSize: 16, color: '#880000' }}>提交</Text>
          </TouchableOpacity>
        </View>
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: theme_app.bg_color
  },
  lineStyle: {
    width: screenWidth - 120,
    height: 40,
    flexDirection: 'row',
    alignItems: 'center'
  }
})

function select(store) {
  return { user_info: store.userInfo.user_info }
}

export default connect(select)(ArrangeDrug)
